﻿#include "dialogprotocalconfig.h"
#include "formconfigtrdp.h"
#include "ui_formconfigtrdp.h"

#include <QDateTime>
#include <QStandardItemModel>
#include"Tool/qfilehelper.h"
#include <Tool/MsgGenerate.h>
FormConfigTRDP::FormConfigTRDP(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormConfigTRDP)
{
    ui->setupUi(this);
    connectAllSlots();

    _timer.start(500);
    this->setWindowIcon(QIcon(":/src/icon/icon_64/train.svg"));
}

FormConfigTRDP::~FormConfigTRDP()
{
    if(_model!=nullptr)
    {
        _model->clear();
        delete _model;
    }
    if(_client.state()==QAbstractSocket::ConnectedState)
    {
        _client.Disconnect();
    }
    delete ui;
}

void FormConfigTRDP::SetTCPServerInfo(const QString &strip, const QString &strPort)
{
    _client.SetTcpInfo(strip,strPort.toInt());
}

void FormConfigTRDP::connectAllSlots()
{
    connect(ui->btn_connect,&QPushButton::clicked,this,&FormConfigTRDP::on_btn_connect_Clicked);
    connect(ui->btn_disconnect,&QPushButton::clicked,this,&FormConfigTRDP::on_btn_disconnect_Clicked);
    connect(ui->btn_confifSel,&QPushButton::clicked,this,&FormConfigTRDP::on_btn_configSel_Clicked);
    connect(ui->btn_configSend,&QPushButton::clicked,this,&FormConfigTRDP::on_btn_configSend_Clicked);
    connect(ui->btn_cardInit,&QPushButton::clicked,this,&FormConfigTRDP::on_btn_cardInit_Clicked);
    connect(&_timer,&QTimer::timeout,this,&FormConfigTRDP::HandleTimer);
    connect(&_client,&TcpClient::TcpMsg,this,&FormConfigTRDP::OnLogMsg);

}
void FormConfigTRDP::OnLogMsg(const QString &logmsg)
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString strlog = currentDateTime.toString("yyyy/MM/dd hh:mm:ss ")+logmsg;
    ui->plainTextEdit->appendPlainText(strlog);
}

void FormConfigTRDP::HandleTimer()
{
    //tcp连接显示
    if(_client.state()==QAbstractSocket::ConnectedState)
    {
        ui->btn_connect->setEnabled(false);
        ui->btn_disconnect->setEnabled(true);
        ui->btn_configSend->setEnabled(true);
        ui->btn_cardInit->setEnabled(true);
    }
    else
    {
        ui->btn_connect->setEnabled(true);
        ui->btn_disconnect->setEnabled(false);
        ui->btn_configSend->setEnabled(false);
        ui->btn_cardInit->setEnabled(false);
    }

}
void FormConfigTRDP::on_btn_connect_Clicked()
{
    _client.connectServer();
}

void FormConfigTRDP::on_btn_disconnect_Clicked()
{
    _client.Disconnect();
}

void FormConfigTRDP::on_btn_configSel_Clicked()
{
    QString fileName = QFileHelper::FileSelect();
    if(fileName.isEmpty())
        return;

    xlsxhelper.OpenXLSXFile(fileName);
    DialogProtocalConfig config;
    QStringList sheetNames =xlsxhelper.GetSheetNames();
    config.SetSheetName(sheetNames);
    int SheetResult= config.exec();
    if(SheetResult==QDialog::Accepted)
    {
        _configSheetName = config._selectItem;
        Readconfig(_configSheetName);
        ShowTRDPConfigData();
    }
    else
    {
        return ;
    }

}

void FormConfigTRDP::on_btn_configSend_Clicked()
{
    if(_trdpCongigs.isEmpty())
    {
        OnLogMsg(QString::fromLocal8Bit("端口配置数据为空请先加载数据。"));
        return;
    }
    for (int i = 0; i < _trdpCongigs.size(); ++i) {
        QString strdata;
        QString strMSg = QString(_trdpCongigs[i].ToJsonString().c_str());
        strdata= messageGenarate::GenerateConfigMsg(MSG_CONTENT::CONFIG,strMSg);
        _client.sendData(strdata);

    }
}

void FormConfigTRDP::on_btn_cardInit_Clicked()
{
    QString strdata;
    QString strMSg;
    strdata= messageGenarate::GenerateConfigMsg(MSG_CONTENT::INITTRDP,strMSg);
    _client.sendData(strdata);
}

void FormConfigTRDP::Readconfig(const QString &configSheetName)
{
    _trdpCongigs.clear();

    xlsxhelper.SetCurrentSheetName(configSheetName);
    xlsxhelper.ReadHeader();
    xlsxhelper.ReadDataByHeaders();

    //读取配置内容
    QMap<QString,QList<QString>> configdata;
    xlsxhelper.GetUsefulData(configdata);
    int nmaxRow=xlsxhelper.GetDataMaxRow(configdata);
    qDebug()<<"useful data count :"<<nmaxRow<<endl;
    TRDPconfig tempConfig;
    try
    {
        for(int i=0;i<nmaxRow;i++)
        {
            //和excel字段对应且固定
            tempConfig.ncomid= configdata["comid"][i].toInt();
            tempConfig.niface= configdata["iface"][i].toInt();
            tempConfig.nDataSetSize= configdata["datasetsize"][i].toInt();
            tempConfig.strSourceIP= configdata["sourceip"][i].toStdString();
            tempConfig.strDestIP= configdata["destip"][i].toStdString();
            tempConfig.npdcircle= configdata["circle"][i].toInt();

            _trdpCongigs.append(tempConfig);
        }
    }
    catch (...)
    {
        OnLogMsg("按标题读取读取excel异常");
        qDebug()<<xlsxhelper.GetHeaders()<<endl;
    }

    OnLogMsg(QString::fromLocal8Bit("读取配置完成."));
}

void FormConfigTRDP::ShowTRDPConfigData()
{
    if(_model==nullptr)
    {
        _model = new QStandardItemModel(); //在使用时不能被释放，否则数据无法显示
    }
    else
    {
        _model->clear();
    }
    QStringList headers  ={};
    headers<<"iface"<<"comid"<<"datasetsize"<<"circle"<<"sourceip"<<"destip";
    int ncolumnCount =headers.count();
    int nrowcount =_trdpCongigs.count();

    _model->setColumnCount(ncolumnCount);
    _model->setHorizontalHeaderLabels(headers);  //表头
    qDebug()<<headers<<endl;
    for (int i = 0; i < nrowcount; ++i)
    {
        TRDPconfig config = _trdpCongigs[i];
        QStandardItem* item1 = new QStandardItem(QString::number(config.niface));
        _model->setItem(i, 0, item1);
        QStandardItem* item2 = new QStandardItem(QString::number(config.ncomid));
        _model->setItem(i, 1, item2);
        QStandardItem* item3 = new QStandardItem(QString::number(config.nDataSetSize));
        _model->setItem(i, 2, item3);
        QStandardItem* item4 = new QStandardItem(QString::number(config.npdcircle));
        _model->setItem(i, 3, item4);
        QStandardItem* item5 = new QStandardItem(QString(config.strSourceIP.c_str()));
        _model->setItem(i, 4, item5);
        QStandardItem* item6 = new QStandardItem(QString(config.strDestIP.c_str()));
        _model->setItem(i, 5, item6);

    }

    ui->tableView->setModel(_model);
    ui->tableView->resizeColumnsToContents();
}

void FormConfigTRDP::closeEvent(QCloseEvent *event)
{
    if(_client.state()==QAbstractSocket::ConnectedState)
    {
        _client.Disconnect();
    }
}
